﻿using System;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.SceneManagement;

public class MySceneManager : MonoBehaviour
{
    public static MySceneManager Instance;
    Scene curScene;
    private void Awake()
    {
        if (Instance == null)
            Instance = this;
        else
            Destroy(gameObject);
    }         

    public void LoadSceneByNet(string sceneName)
    {
        if (!NetworkManager.Singleton.IsServer)
        {
            Debug.Log("only server can load scene");
            return;
        }

        var manager = NetworkManager.Singleton.SceneManager;
        manager.LoadScene(sceneName, LoadSceneMode.Additive);

        // 移除可能存在的旧处理器
        manager.OnLoadEventCompleted -= OnSceneLoaded;
        manager.OnLoadEventCompleted += OnSceneLoaded;
    }

    private void OnSceneLoaded(string sceneName, LoadSceneMode loadMode,
        System.Collections.Generic.IReadOnlyList<ulong> clientsCompleted,
        System.Collections.Generic.IReadOnlyList<ulong> clientsTimedOut)
    {        
        var newScene = SceneManager.GetSceneByName(sceneName);
        if (newScene.IsValid())
        {
            if(curScene.IsValid() && curScene.isLoaded)
                NetworkManager.Singleton.SceneManager.UnloadScene(curScene);
            SceneManager.SetActiveScene(newScene);
            curScene = newScene;
        }
        NetworkManager.Singleton.SceneManager.OnLoadEventCompleted -= OnSceneLoaded;
    }

    public void LoadSceneAsync(string sceneName, LoadSceneMode loadSceneMode = LoadSceneMode.Additive)
    {
        if (curScene.IsValid() && SceneManager.GetSceneByName(sceneName).isLoaded)
        {            
            Debug.Log($"load scene {sceneName} repeat");
            return;
        }
            
        var operation = SceneManager.LoadSceneAsync(sceneName, loadSceneMode);
        if (operation != null)
        {
            operation.completed += (op) =>
            {
                var newScene = SceneManager.GetSceneByName(sceneName);

                if (newScene.IsValid())
                {
                    SceneManager.SetActiveScene(newScene);
                    curScene = newScene;
                    //遍历已经加载的场景
                    for (int i = SceneManager.sceneCount-1; i >=0 ; i--)
                    {
                        var _scene = SceneManager.GetSceneAt(i);
                        if (_scene.name != "Persistent" && _scene.name != sceneName && _scene.isLoaded)
                        {
                            SceneManager.UnloadSceneAsync(_scene);
                        }
                    }
                }
                else
                {
                    Debug.Log("Load scene error " + sceneName + Environment.StackTrace);
                }
            };
        }
    }
}
